import { NextResponse } from 'next/server'
import { ProductCopy } from '@/types/Model'
import prisma from '@/lib/db'
import { verifyToken } from '@/lib/auth'

// GET all copies for a topic
export async function GET(
  request: Request,
  { params }: { params: { topic_id: string } }
): Promise<Response> {
  try {
    const { searchParams } = new URL(request.url)
    const token = request.headers.get('Authorization')?.split(' ')[1]
    const payload = token ? verifyToken(token) : null;
  
    if (!payload) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const topicId = searchParams.get('topic_id') || params.topic_id
    
    if (!topicId) {
      return NextResponse.json(
        { error: 'Topic ID is required' },
        { status: 400 }
      )
    }

  

    const topicCopies = await prisma.productCopy.findMany({
      where: {
        topic_id: topicId,
      },
      select: {
        id: true,
        topic_id: true,
        title: true,
        intro: true,
        status: true,
        cjsj: true,
        pxh: true
      },
      orderBy: {
        pxh: 'asc'
      }
    })
    
    return NextResponse.json(topicCopies, { status: 200 })
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to fetch copies' },
      { status: 500 }
    )
  }
}

// POST create new copy
export async function POST(request: Request): Promise<Response> {
  try {
    const { searchParams } = new URL(request.url)
    const token = request.headers.get('Authorization')?.split(' ')[1]
    const payload = token ? verifyToken(token) : null;
  
    if (!payload) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json()

    // Validate required fields
    if (!body.topic_id) {
      return NextResponse.json(
        { error: 'Topic ID is required' },
        { status: 400 }
      )
    }
    if (!body.title) {
      return NextResponse.json(
        { error: 'Title is required' },
        { status: 400 }
      )
    }

    // Get the max pxh for the topic
    const maxPxhCopy = await prisma.productCopy.findFirst({
      where: {
        topic_id: body.topic_id
      },
      orderBy: {
        pxh: 'desc'
      },
      select: {
        pxh: true
      }
    })

    const newPxh = (maxPxhCopy?.pxh || 0) + 1
    const newCopy = await prisma.productCopy.create({
      data: {
        id: crypto.randomUUID(),
        product_id: body.product_id,  
        topic_id: body.topic_id,
        title: body.title,
        intro: body.intro || '',
        status: '文案编辑中',
        cjsj: new Date(),
        pxh: newPxh,
        content: body.content,
        md_content:''
      }
    })

    
    return NextResponse.json(newCopy, { status: 201 })
  } catch (error) {
    console.error('Error creating copy:', error)
    return NextResponse.json(
      { error: 'Failed to create copy' },
      { status: 500 }
    )
  }
}

// PUT update copy
export async function PUT(request: Request): Promise<Response> {
  try {
    const token = request.headers.get('Authorization')?.split(' ')[1]
    const payload = token ? verifyToken(token) : null;
  
    if (!payload) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }


    const body = await request.json()
    
    // 先查询文案所属用户
    const copy = await prisma.productCopy.findUnique({
      where: { id: body.id }
    })
    
    if (!copy) {
      return NextResponse.json(
        { error: '未找到文案' },
        { status: 404 }
      )
    }
    
    // 检查当前用户是否有权限修改
    // if (copy.user_id !== userid) {
    //   return NextResponse.json(
    //     { error: '无权修改他人文案' },
    //     { status: 403 }
    //   )
    // }
    
    // Validate required fields
    if (!body.id) {
      return NextResponse.json(
        { error: 'Copy object with ID is required' },
        { status: 400 }
      )
    }

    const updatedCopy = await prisma.productCopy.update({
      where: {
        id: body.id
      },
      data: body
    })

    
    return NextResponse.json(updatedCopy, { status: 200 })
  } catch (error) {
    console.error('Error updating copy:', error)
    return NextResponse.json(
      { error: 'Failed to update copy' },
      { status: 500 }
    )
  }
}
